package jalus.blog;

import jalus.Action;
import jalus.FMConfigureFactory;
import jalus.model.AccessLog;
import jalus.service.AccessLogService;
import jalus.service.ConfigureService;
import jalus.service.PostService;
import jalus.service.WidgetService;
import jalus.utils.MyUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * 显示PV统计信息
 * @author dongliu
 *
 */
public class StatisticServlet extends Action{
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!(userService.isUserLoggedIn() && userService.isUserAdmin())){
			error();
			return;
		}
		User user = userService.getCurrentUser();
		
		Date currentDate = new Date();
		
		String dateString = req.getParameter("date");
		Date date = MyUtils.parseDateCCT(dateString, "yyyy-MM-dd");
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		List<Date> dateList = new ArrayList<Date>(7);
		int diff = (int)(currentDate.getTime()-date.getTime())/(24*60*60*1000);
		if(diff >3){
			diff = 3;
		}
		calendar.add(Calendar.DATE, diff+1);
		for(int i=0; i<7; i++){
			calendar.add(Calendar.DATE, -1);
			dateList.add(calendar.getTime());
		}
		
		AccessLogService accessLogService = AccessLogService.getInstance();
		List<AccessLog> accessList = accessLogService.getAccessLogListByDate(date);
		
		Template template = FMConfigureFactory.getFMConfigure().getTemplate("statistic.html");
		
		Map root = new HashMap();
		root.put("accesslist", accessList);
		root.put("user", user);
		root.put("focustab", "statistic");
		root.put("dateList", dateList);
		root.put("idx", diff);
		/* 传递变量 */
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("userService", userService);
		root.put("uri", req.getRequestURI());
		
		/* sidebar */
		WidgetService.getInstance().getSpecifiedWidget(root, "taglist", "recentpost", "recentcomment");
		
        resp.setCharacterEncoding("utf-8"); 
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        try {
        	template.process(root, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		}
        out.flush();
	}
}
